package middleware

import (
	"encoding/json"
	"git.mycaigou.com/gfyx/common/authorize"
	"git.mycaigou.com/gfyx/common/cache"
	"git.mycaigou.com/gfyx/common/http_client"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
)

type ZhanTuUserData struct {
	Status bool `json:"status"`
	Data   struct {
		UserInfo struct {
			UserId  string `json:"user_id"`
			Name    string `json:"name"`
			Account string `json:"account"`
		} `json:"user_info"`
	} `json:"data"`
}

const ZhanTuTokenCacheKey = "gfyx:zhantu:auth-token:"

// AuthorizeForZhanTu 战图登录态的认证
func AuthorizeForZhanTu() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		authToken := ctx.DefaultQuery("auth-token", "")
		if authToken == "" {
			authToken = ctx.GetHeader("auth-token")
		}
		if authToken == "" {
			response(ctx, errcode.COMMON_TOKEN_ERROR, "未登录")
			return
		}

		cacheRedis, _ := cache.Redis()
		cacheUserInfo, err := cacheRedis.Get(ctx, ZhanTuTokenCacheKey+authToken)
		if err != nil {
			response(ctx, errcode.COMMON_TOKEN_ERROR, err.Error())
			return
		}
		var userInfo ZhanTuUserData
		if cacheUserInfo == "" {
			apiHost := stark.Configer.(stark.ApolloConfigerIface).GetStringValue("zhantu_api_host", "")
			url := apiHost + "/auth/get-user-auth"
			http_client.New().Post(ctx, url, map[string]interface{}{"token": authToken}, map[string]string{"Content-Type": "application/json"}).EndStruct(&userInfo)
			if userInfo.Status == false {
				response(ctx, errcode.COMMON_TOKEN_ERROR, "战图用户登录态已失效，请重新登录")
				return
			}
			// 转成 json 存储
			marshal, _ := json.Marshal(userInfo)
			_, _ = cacheRedis.Set(ctx, ZhanTuTokenCacheKey+authToken, string(marshal), true, 3600)
		} else {
			_ = json.Unmarshal([]byte(cacheUserInfo), &userInfo)
		}
		// todo 实现 配置，并且不用传租户 code
		ctx.Set(authorize.TENANT_CODE_KEY, "ycg")
		ctx.Set(authorize.ZhanTuUserName, userInfo.Data.UserInfo.Name)
		ctx.Next()
	}
}
